// 判断是否叶子节点
const isLeaf = (data, prop) => {
    return !(Array.isArray(data[prop]) && data[prop].length > 0)
}

// 创建 node 节点
export const renderNode = (h, data, context) => {
    const { props } = context
    const cls = ['org-tree-node']
    const childNodes = []
    const children = data[props.props.children]

    if (isLeaf(data, props.props.children)) {
        cls.push('is-leaf')
    } else if (props.collapsable && !data[props.props.expand]) {
        cls.push('collapsed')
    }

    childNodes.push(renderLabel(h, data, context))

    if (!props.collapsable || data[props.props.expand]) {
        childNodes.push(renderChildren(h, children, context))
    }

    return h('div', {
        domProps: {
            className: cls.join(' ')
        }
    }, childNodes)
}

// 创建展开折叠按钮
export const renderBtn = (h, data, { props, listeners }) => {
    const expandHandler = listeners['on-expand']

    let cls = ['org-tree-node-btn']

    if (data[props.props.expand]) {
        cls.push('expanded')
    }

    return h('span', {
        domProps: {
            className: cls.join(' ')
        },
        on: {
            click: e => expandHandler && expandHandler(e, data)
        }
    })
}

// 创建 label 节点
export const renderLabel = (h, data, context) => {
    const { props, listeners } = context
    const label = data[props.props.label]
    const renderContent = props.renderContent

    // event handlers
    const clickHandler = listeners['on-node-click']
    const dblClickHandler = listeners['on-node-dblclick']
    const mouseOverHandler = listeners['on-node-mouseover']
    const mouseOutHandler = listeners['on-node-mouseout']
    const keyUpHandler = listeners['on-node-keyup']
    const refresh = listeners['on-refresh']

    const childNodes = []
    if (typeof renderContent === 'function') {
        let vnode = renderContent(h, data)

        vnode && childNodes.push(vnode)
    } else {
        childNodes.push(label)
    }

    if (props.collapsable && !isLeaf(data, props.props.children)) {
        childNodes.push(renderBtn(h, data, context))
    }

    const cls = ['org-tree-node-label-inner']
    let { labelWidth, labelClassName, selectedClassName, selectedKey } = props
    if (typeof labelWidth === 'number') {
        labelWidth += 'px'
    }

    if (typeof labelClassName === 'function') {
        labelClassName = labelClassName(data)
    }

    labelClassName && cls.push(labelClassName)

    // add selected class and key from props
    if (typeof selectedClassName === 'function') {
        selectedClassName = selectedClassName(data)
    }

    selectedClassName && selectedKey && data[selectedKey] && cls.push(selectedClassName)

    return h('div', {
        domProps: {
            className: 'org-tree-node-label'
        },
        attrs: {
            id: 'node'+data.id
        },
        on: {
            'dblclick': e => { addIput(data, refresh) },
            'click': e => { clickNode(data, keyUpHandler, refresh);clickHandler(e, data)},
            'mouseover': e => mouseOverHandler && mouseOverHandler(e, data),
            'mouseout': e => mouseOutHandler && mouseOutHandler(e, data)
        }
    }, [h('div', {
        domProps: {
            className: cls.join(' ')
        },
        style: { width: labelWidth },
    }, childNodes)])
}

// 创建 node 子节点
export const renderChildren = (h, list, context) => {
    if (Array.isArray(list) && list.length) {
        const children = list.map(item => {
            return renderNode(h, item, context)
        })

        return h('div', {
            domProps: {
                className: 'org-tree-node-children'
            }
        }, children)
    }
    return ''
}
 // 点击节点
const clickNode = (data, keyUpHandler, refresh) => {
    var nodes = document.getElementsByClassName('org-tree-node-label');
    for (let i in nodes){
        if (nodes[i].classList){
            nodes[i].classList.remove('checked');
        }
    }
    document.getElementById('node' + data.id).classList.add("checked");
    document.onkeyup = (event) => {
        var e = event || window.event || arguments.callee.caller.arguments[0];
        if (e.keyCode === 46){ // 键盘的del键
            keyUpHandler(data)
        } else if (e.keyCode === 13){ // 回车键
            addIput(data, refresh);
        } else if (e.keyCode === 40) { // 向下方向键
            var id = 'n' + new Date().getTime();
            var nodeObj = {
                id: id,
                label: "节点",
                expand: true,
            };
            if (data.children){
                data.children.push(nodeObj);
            }else {
                data.children = [nodeObj];
            }
            refresh();
        }
        
    }
 }

// 双击节点时，添加输入框
const addIput = (data, refresh) => {
    var input = document.createElement("input");
    input.setAttribute("class", "org-tree-input");
    input.onblur=function(){
        if (this.value){
            data.label = this.value;
        }
        this.remove();
        refresh();
    }
    var nodeEl = document.getElementById('node'+data.id);
    nodeEl.appendChild(input);
    input.focus();
}

export const render = (h, context) => {
    const { props } = context
    return renderNode(h, props.data, context)
}

export default render
